package main

import (
	"fmt"
	"github.com/Masterminds/sprig/v3"
	_ "html/template"
	"os"
	config2 "parse-template/src/config"
	"parse-template/src/script"
	utils2 "parse-template/src/utils"
	"path"
	"path/filepath"
	"strings"
	"text/template"
)

func main() {
	context := config2.ApplicationContext{}
	config2.ParseApplicationConfig(&context)
	// 解析模板
	data := config2.ParseTemplateValueConfig(&context)
	utils2.DeleteDirFile(context.Config.Template.OutPath)
	// 加载模板
	templateFiles, _ := utils2.WalkDir("template/")
	for _, tmplFile := range templateFiles {
		commonTemplFiles := GetCommonParseFiles()
		var tmpl = []string{tmplFile}
		if commonTemplFiles == nil || len(commonTemplFiles) == 0 {
			parseTemplate(tmplFile, tmpl, data, context.Config.Template.OutPath)
		} else {
			parseTemplate(tmplFile, append(tmpl, commonTemplFiles...), data, context.Config.Template.OutPath)
		}
	}
}

func parseTemplate(tmplFilePath string, parseFiles []string, data map[string]interface{}, outPath string) {
	name := path.Base(parseFiles[0])
	tmpl, err := template.New(name).Funcs(sprig.TxtFuncMap()).ParseFiles(parseFiles...)
	// 设置模板数据
	utils2.CheckErr(err)
	outPath = outPath + strings.ReplaceAll(tmplFilePath, "template", "")
	outPath = strings.ReplaceAll(outPath, "//", "/")
	outPath = strings.ReplaceAll(outPath, ".tmpl", "")
	outPath = utils2.ConvertLinuxPathSeparator(outPath)
	err = os.MkdirAll(filepath.Dir(outPath), 0755)
	utils2.CheckErr(err)

	file, err := os.OpenFile(outPath, os.O_CREATE|os.O_WRONLY, 0755)
	utils2.CheckErr(err)
	err = tmpl.Execute(file, data)
	utils2.CheckErr(err)

	// 将文件转成unix编码
	errCmd := script.ExecCmdNoStout("dos2unix " + outPath)
	if errCmd != nil {
		fmt.Println("dos2unix命令执行失败, 请确保linux已经安装dos2unix, 安装命令如下")
		fmt.Println("  centos: yum install dos2unix -y\n  ubuntu: apt install dos2unix -y")
		panic(errCmd)
	}
}

func GetCommonParseFiles() []string {
	files, _ := utils2.WalkDir("common/")
	return files
}
